﻿using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Phoenix.Xna.Framework.Graphics;

namespace Phoenix.Xna.Framework.Components.Terrain
{
    public struct TerrainPrimitive
    {
        private int _indice1;
        private int _indice2;
        private int _indice3;

        public int Indice1
        {
            get { return _indice1; }
            set { _indice1 = value; }
        }
        public int Indice2
        {
            get { return _indice2; }
            set { _indice2 = value; }
        }
        public int Indice3
        {
            get { return _indice3; }
            set { _indice3 = value; }
        }

        public TerrainPrimitive(int indice1, int indice2, int indice3)
        {
            _indice3 = indice3;
            _indice2 = indice2;
            _indice1 = indice1;
        }

        public Plane GetPlane(List<VertexPositionNormal> vertices)
        {
            return new Plane(vertices[Indice1].Position, vertices[Indice2].Position, vertices[Indice3].Position);
        }

        public Vector3 GetNormal(List<VertexPositionNormal> vertices)
        {
            try
            {
                return new Plane(vertices[Indice1].Position, vertices[Indice2].Position, vertices[Indice3].Position).Normal;
            }
            catch { return Vector3.Zero; }
        }

        public void SetNormal(List<VertexPositionNormal> vertices)
        {
            if (Indice1 < vertices.Count && Indice2 < vertices.Count && Indice3 < vertices.Count)
            {
                Vector3 normal = GetNormal(vertices);
                VertexPositionNormal vertex = vertices[Indice1];
                vertex.Normal += normal;
                vertex.Normal.Normalize();
                vertices[Indice1] = vertex;
                vertex = vertices[Indice2];
                vertex.Normal += normal;
                vertex.Normal.Normalize();
                vertices[Indice2] = vertex;
                vertex = vertices[Indice3];
                vertex.Normal += normal;
                vertex.Normal.Normalize();
                vertices[Indice3] = vertex;
            }
        }
    }
}
